// formPackage/pages/newHousePublishModule/newHousePublishThree/newHousePublishThree.js
import { queryNewHouseFormatList, createNewHouseFloor, queryNewHouseFloorDetail, updateNewHouseFloor } from "../../../../service/publish_service"
import { chooseAndUploadQiniuActicon } from "../../../../service/upload_service"
import debounce from "../../../../tools/debounce"
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeStyle: "",
    btnTitle: "楼栋保存",
    showDeliveryTimePop: false,//交付时间选择
    singlePopType: "",//单项弹窗类型
    singlePopTitle: "选择",//单项弹窗标题
    showSinglePop: false,//弹出单项弹窗
    minDate: new Date(2000, 12, 31).getTime(),
    maxDate: new Date(2050, 12, 31).getTime(),
    timePopType: "deliveryTime",
    formData: {
      houseNumber: "",
      consignTime: "",//交付时间
      ladderRatio: "",//梯户比
      layers: "",//总层数
      name: "",//楼栋名称
      preSaleProvePic: "",//预售许可证图片
      preSaleProveTitle: "",//预售许可证名字
      saleStatus: "",//销售状态
      unit: "",//单元数
      formats: [],//绑定的户型数组id
    },
    houseNumber: "",
    formatList: [

    ],
    floorId: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      houseNumber: options.houseNumber
    })
    if (options.id) {
      this.setData({
        floorId: options.id
      })
      this.queryNewHouseFloorDetail();
    }

    this.queryNewHouseFormatList();
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
  },
  //查询已有楼栋数据:
  queryNewHouseFloorDetail() {
    queryNewHouseFloorDetail(this.data.floorId).then(res => {
      wx.hideLoading();
      console.log("JJLog:已有楼栋数据:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          formData: res.data.flat,
          'formData.formats': res.data.formats || [],
          btnTitle: "楼栋更新",
        })
        //已选户型绑定:
        setTimeout(() => {
          this.bindFormats(res.data.formats);
        }, 1500);
      }
    }).catch(err => {
      wx.hideLoading();
      console.log("JJLog:楼栋数据失败:" + JSON.stringify(err));
    })
  },
  //已选户型绑定:
  bindFormats(formats) {

    if (formats.length > 0) {
      let arr = this.data.formatList;
      formats.forEach((i) => {
        arr.forEach((j) => {
          if (i == j.id) {
            j.isChoose = true
          }
        })
      })
      this.setData({
        formatList: arr
      })
    }
  },

  //查询已有户型列表
  queryNewHouseFormatList() {
    queryNewHouseFormatList(this.data.houseNumber).then(res => {
      wx.hideLoading();
      console.log("JJLog:已有户型:" + JSON.stringify(res));
      if (res.code == 200) {
        // this.setData({
        //   formatList: res.data || []
        // })
        if (res.data && res.data.length > 0) {
          res.data.forEach((item) => {
            item.isChoose = false
          })
          this.setData({
            formatList: res.data
          })
        }
      }
    }).catch(err => {
      wx.hideLoading();
      console.log("JJLog:户型列表失败:" + JSON.stringify(err));
    })
  },


  // 单项输入回调:
  inputCellChange(e) {
    let type = e.detail.key;
    let changeValue = `formData.${type}`;
    this.setData({
      [changeValue]: e.detail.value
    })
  },






  //选择户型;
  selectFormat(e) {
    let index = e.currentTarget.dataset.index;
    let arr = this.data.formatList;
    arr.forEach((i, idx) => {
      if (idx == index) {
        i.isChoose = !i.isChoose
      }
    })
    this.setData({
      formatList: arr
    })
  },
  //单项选择弹窗弹出:
  singleSelectPop(e) {
    let type = e.currentTarget.dataset.type;
    if (type == "consignTime") {
      //交付时间
      this.setData({
        showDeliveryTimePop: true
      })
    } else if (type == "saleStatus") {
      //销售状态
      this.setData({
        showSinglePop: true,
        singlePopType: type,
        singlePopTitle: "楼栋状态"
      })
    }
  },
  //单项选择回调:
  singlePopSelectCallback(e) {
    console.log('JJLog:单项选择回调:' + JSON.stringify(e));
    let result = e.detail.result;
    let type = e.detail.type;
    let changeValue = `formData.${type}`;
    this.setData({
      [changeValue]: result.value,
      showSinglePop: false
    })
  },

  //交付时间选择回调;
  deliveryTimeSure(e) {
    console.log("JJLog:交付时间回调:" + JSON.stringify(e));
    let timeStr = e.detail.timeStr;
    this.setData({
      'formData.consignTime': timeStr,
      showDeliveryTimePop: false
    })
  },
  timePopHidden() {
    this.setData({
      showDeliveryTimePop: false
    })
  },
  singlePopHide() {
    this.setData({
      showSinglePop: false
    })
  },

  //上传预售许可证图片
  pushFloorImg() {
    chooseAndUploadQiniuActicon('format').then(res => {
      console.log("JJLog:图片上传成功:" + JSON.stringify(res));
      wx.showToast({
        title: '上传成功',
      })
      this.setData({
        'formData.preSaleProvePic': res.complateUrl
      })
    }).catch(err => {
      console.log("JJLog:图片上传失败:" + JSON.stringify(err));
      wx.showToast({
        title: '图片上传失败',
        icon: "none"
      })
    })
  },

  //创建楼栋
  pushBasicInfo() {
    let formatArr = this.data.formatList;
    if (formatArr.length > 0) {
      let arr = [];
      formatArr.forEach((item) => {
        if (item.isChoose) {
          arr.push(item.id);
        }
      })
      this.setData({
        'formData.formats': arr
      })
    }
    this.setData({
      'formData.houseNumber': this.data.houseNumber
    })

    if (this.data.floorId) {
      //更新数据:
      debounce(this.updateFloorData);
    } else {
      //创建数据
      debounce(this.createFloorData);
    }

  },

  //创建楼栋提交:
  createFloorData() {
    wx.showLoading({
      title: '保存中...',
    })
    createNewHouseFloor(this.data.formData).then(res => {
      wx.hideLoading();
      console.log("JJLog:保存一个楼栋信息:" + JSON.stringify(res));
      if (res.code == 200) {
        wx.showToast({
          title: '保存成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 0,
          })
        }, 2000);
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
      })
    })
  },

  //更新楼栋提交:
  updateFloorData() {
    wx.showLoading({
      title: '保存中...',
    })
    updateNewHouseFloor(this.data.formData).then(res => {
      wx.hideLoading();
      console.log("JJLog:更新一个楼栋信息:" + JSON.stringify(res));
      if (res.code == 200) {
        wx.showToast({
          title: '更新成功',
          icon: "success"
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 0,
          })
        }, 2000);
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
      })
    })
  },

})